package com.epfly.promo.activity.impl.discount;

import com.epfly.iface.promo.activity.enums.DiscountTypeEnum;
import com.epfly.promo.activity.dao.ActivityBargainFoodMapper;
import com.epfly.promo.activity.entity.ActivityBargainFoodEntity;
import com.epfly.promo.activity.entity.ActivityEntity;
import com.epfly.promo.activity.entity.ActivityRuleEntity;
import com.epfly.promo.activity.feign.DataRestaurantFeignService;
import com.ifood.model.goods.param.response.food.FoodInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 7.特价菜;
 * {@link DiscountTypeEnum#FOOD_BARGAIN}
 */
@Service
public class FoodBargainDiscountFunction extends AbstractDiscountFunction {

    @Resource
    private ActivityBargainFoodMapper activityBargainFoodMapper;

    @Resource
    private DataRestaurantFeignService dataRestaurantFeignService;

    @Override
    public BigDecimal doApply(ActivityWrapper activityWrapper, ActivityRuleEntity ruleEntity) {
        // 优惠总金额
        BigDecimal totalRebate = BigDecimal.ZERO;

        ActivityEntity activityEntity = activityWrapper.getActivityEntity();

        // 查出所有享受折扣的菜品
        List<ActivityBargainFoodEntity> bargainFoodEntities = activityBargainFoodMapper.findByActivityIdAndFoodIdList(activityEntity.getId(), activityWrapper.getFoodIdList());

        if (CollectionUtils.isNotEmpty(bargainFoodEntities)) {
            Map<String, BigDecimal> foodRebateAmountMap = bargainFoodEntities.stream().collect(Collectors.toMap(ActivityBargainFoodEntity::getRelationId, ActivityBargainFoodEntity::getBargainAmount));

            List<FoodInfo> foodList = dataRestaurantFeignService.findFoodByFoodIdList(foodRebateAmountMap.keySet());
            for (FoodInfo foodInfo : foodList) {
                BigDecimal marketPrice = foodInfo.getVipPrice(); // vipPrice 是现价、市价，即现在的价格，非会员价，非优惠价。
                BigDecimal rebatePrice = foodRebateAmountMap.get(foodInfo.getFoodId());
                if (rebatePrice.compareTo(marketPrice) < 0) { // 折扣价小于市价
                    totalRebate = totalRebate.add(marketPrice.subtract(rebatePrice));
                }
            }
        }
        return totalRebate;
    }


    @Override
    public Byte getDiscountType() {
        return DiscountTypeEnum.FOOD_BARGAIN.getKey();
    }
}
